package com.citygis.securitysystem.system.services;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.citygis.securitysystem.system.entity.Users;
import com.citygis.securitysystem.system.mapper.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ClassName: MyUserDetailsService 
 * @Description: TODO
 * @author: liuzg
 * @Date: 2021/1/21 9:18
 * @Version: v1.0
 */
@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 调用usersMapper方法，根据用户名查询数据库
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        // // where username = ?
        queryWrapper.eq("username", username);
        Users users = userDao.selectOne(queryWrapper);
        //判断
        if (users == null) {//数据库没有用户名，认证失败
            throw new UsernameNotFoundException("用户名不存在！");
        }
        List<GrantedAuthority> auths =
                AuthorityUtils.commaSeparatedStringToAuthorityList("admin,ROLE_sale");
        return new User(users.getUsername(),
                new BCryptPasswordEncoder().encode(users.getPassword()),auths);
    }
}
